﻿
using CommonServiceLocator;
using MS.Common;
using MS.Common.Context;
using MS.Common.Helpers;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Threading;
using Wpf.Models;

namespace JHECIS.NursingRecord.Common
{
    /// <summary>
    /// 接口工具类 
    /// </summary>
    internal class InterfaceToolHelper
    {
        #region 变量
        /// /// <summary>
        /// 延迟加载对象 
        /// </summary>
        private static readonly Lazy<InterfaceToolHelper> _lazy = new Lazy<InterfaceToolHelper>(() => new InterfaceToolHelper(), LazyThreadSafetyMode.PublicationOnly);

        /// <summary>
        /// 单例对象 
        /// </summary>
        public static InterfaceToolHelper Instance => _lazy.Value;
       
        /// <summary>
        /// Rest请求操作接口  2022-01-24 
        /// </summary>
        private readonly IRestClient restClient;
       
        #endregion
   
        private InterfaceToolHelper()
        {
           
            restClient = ServiceLocator.Current.GetInstance<IRestClient>();
           
        }     
        /// <summary>
        /// 转换
        /// </summary>
        /// <param name="script"></param>
        /// <returns></returns>
        public string Convert(ScriptContent script)
        {
            var result = string.Empty;
            try
            {
                using (CodeTimer timer = new CodeTimer(script.FunctionName))
                {
                    var resource = "api/JavaScript/Convert";
                    if (script.ScriptType == 1)
                    {
                        resource = "api/PythonScript/Convert";
                    }
                    var request = new RestRequest(resource, Method.POST);
                    var json = JsonConvert.SerializeObject(script);
                    LogHelper.GetLogHelper().Trace("接口参数：" + script.Data);
                    request.AddJsonBody(json); // replaces matching token in request.Resource

                    var response = restClient.Execute(request);
                    var responseApi = JsonConvert.DeserializeObject<ResponseApi<string>>(response.Content);
                    result = responseApi.data;
                }
            }
            catch (Exception ex)
            {
                LogHelper.GetLogHelper().Error(ex);
            }

            return result;
        }

        /// <summary>
        /// 通过接口编码查询接口内容
        /// </summary>
        /// <param name="interfaceCode"></param>
        /// <returns></returns>
        public InterfaceToolEntity GetInterfaceToolByCode(string interfaceCode)
        {
            InterfaceToolEntity result =null;
            try
            {
                var request = new RestRequest("api/InterfaceTool/GetInterfaceToolByCode", Method.GET);
                request.AddParameter("interfaceCode", interfaceCode);
                var response = restClient.Execute(request);
                var responseApi = JsonConvert.DeserializeObject<ResponseApi<InterfaceToolEntity>>(response.Content);
                result = responseApi.data;
            }
            catch (Exception ex)
            {
                LogHelper.GetLogHelper().Error(ex);
            }
            return result;
        }

        /// <summary>
        /// 传入接口方法名，与动态参数获取接口工具方法执行结果
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="funcName"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public CommonResult CallJsConvertDynamic(string funcName, dynamic dy)
        {
            CommonResult result = new CommonResult();
            try
            {
                var jsScript = GetInterfaceToolByCode(funcName);
                if (jsScript != null)
                {
                    string param= JsonConvert.SerializeObject(dy, new JsonSerializerSettings { DateFormatString = "yyyy-MM-dd HH:mm:ss" });
                    var script = new ScriptContent()
                    {
                        FunctionName = jsScript.FUNCTIONNAME,
                        JavaScriptCode = jsScript.JAVASCRIPTCODE,
                        Data = param
                    };
                    string respone = Convert(script);
                    result = JsonConvert.DeserializeObject<CommonResult>(respone);
                    return result;
                }
                else
                {
                    result.Result = false;
                    result.ErrMsg = $"请在接口工具中配置【{funcName}】";
                    return result;
                }
            }
            catch (Exception ex)
            {
                result.Result = false;
                result.ErrMsg = ex.Message;
                return result;
            }
        }
            
    }
}
